package com.schedule.controller;

import com.schedule.Util.PagedGridResult;
import com.schedule.mapper.FileMapper;
import com.schedule.pojo.RespBean;
import com.schedule.service.IFileService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
public class FileController {

    @Autowired
    private IFileService fileService;

    @Autowired
    private FileMapper fileMapper;

    /**
     * 该方法的返回值只能是null，不然日志文件会报错
     * 通过文件名查找文件在数据库中存储的路径
     */
//    @ApiOperation("下载文件")
//    @GetMapping("/download")
//    @ResponseBody
//    public String download(@RequestParam("fileName") String fileName, HttpServletRequest request, HttpServletResponse response) throws IOException {
//        //接收数据 文件名
//        //文件下载
//        //1、加载服务器指定名
//        String realPath = fileMapper.findFile(fileName);  //加载数据库中文件存储的路径
//        FileInputStream is = new FileInputStream(new File(realPath, fileName));  //创建新的文件输入流
//        //2、设置文件下载方式
//        response.reset(); //设置页面不缓存,清空buffer
//        response.setCharacterEncoding("UTF-8"); //字符编码
//        response.setContentType("multipart/form-data"); //二进制传输数据
//        response.setHeader("content-disposition","attachment;filename="+ URLEncoder.encode(fileName,"utf-8"));
//        //3、获取响应输出流
//        PrintWriter writer = response.getWriter();
//        //4、流数据交换
//        IOUtils.copy(is,writer);
//        //5、关闭资源
//        IOUtils.closeQuietly(is);
//        IOUtils.closeQuietly(writer);
//        return  null;
//    }

    @ApiOperation("下载文件")
    @PostMapping("/download")
    @ResponseBody
    public ResponseEntity<ByteArrayResource> down3(@RequestParam("fileName") String fileName) throws Exception {
        String realPath = fileMapper.findFile(fileName);
        byte[] bytes = Files.readAllBytes(new File(realPath,fileName).toPath());
        ByteArrayResource bar = new ByteArrayResource(bytes);
        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .header("Content-disposition", "attachment; filename=" +  URLEncoder.encode(fileName, "UTF-8"))
                .body(bar);
    }

    @ApiOperation("上传文件")
    @PostMapping("/program/upload")
    @ResponseBody
    public RespBean upload(@RequestParam("file") MultipartFile file,HttpServletRequest request)throws Exception {
        System.out.println("file is "+file);
        if (file.isEmpty()) {
            return RespBean.error("上传失败，请选择文件");
        }
        String fileName = file.getOriginalFilename();
        String name = FilenameUtils.getBaseName(fileName); //获得文件的前缀
        String extension = FilenameUtils.getExtension(file.getOriginalFilename()); //获得文件的后缀
        String newFileNamePrefix= name + new SimpleDateFormat("yyyyMMddHHssSSS").format(new Date());
//        String newFileNamePrefix = name;
        String newFileName=newFileNamePrefix+"."+extension;
//        String c = System.getProperty("user.dir"); //获得本电脑的相对路径
//        String filePath = c + "\\src\\main\\resources\\uploadFiles\\";
//        String filePath = "/src/main/resources/uploadFiles/";
        String parentDir = request.getServletContext().getRealPath("upload");
        File parent = new File(parentDir);
        if (!parent.exists()) {
            parent.mkdirs();
        }
        File dest = new File(parent,newFileName);
        try{
            file.transferTo(dest);
            fileMapper.addFile(newFileName,parentDir);
        }catch (Exception e){
            return RespBean.error("上传失败");
        }

//        else if(fileService.addFile(file)){
//            return RespBean.success("上传成功");
//        }
        return RespBean.success("上传成功");
    }

    @ApiOperation("模糊查询")
    @GetMapping("/program/findFileByDim")
    @ResponseBody
    public RespBean findFileByDim(@RequestParam("name") String name){
        List<com.schedule.pojo.File> files = fileMapper.findFileByDim(name);
        if (files != null){
            return RespBean.success("模糊查询文件成功", files);
        }
        return RespBean.error("模糊查询文件失败");
    }

    @ApiOperation("分页查询所有文件")
    @GetMapping("/program/findAll")
    @ResponseBody
    public RespBean findAll(@RequestParam(name="page") Integer page,
                            @RequestParam(name="pageSize") Integer pageSize){
        PagedGridResult files = fileService.findAll(page, pageSize);
        if (files != null){
            return RespBean.success("查询所有文件成功", files);
        }
        return RespBean.error("查询所有文件失败");
    }

    @ApiOperation("根据文件名删除文件")
    @DeleteMapping("/program/delFile")
    @ResponseBody
    public RespBean delFile(@RequestParam(name="filename")String filename){
        if (fileService.delFile(filename)){
            return RespBean.success("删除文件成功");
        }
        return RespBean.error("删除文件失败");
    }

}
